package com.atguigu.gulimall.product.Exception;

import com.atguigu.common.Exception.BizCodeEnums;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handelValueException(MethodArgumentNotValidException e) {
        Map<String, String> hashMap = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            hashMap.put(field, message);
        });
        log.error("数据校验异常:{},异常类型:{}", e.getMessage(), e.getClass());
        return R.error(BizCodeEnums.VALID_EXCEPTION.getCode(), BizCodeEnums.VALID_EXCEPTION.getMessage()).put("data", hashMap);
    }

    //@ExceptionHandler(Throwable.class)
    public R HandelException(Throwable t) {
        log.error("数据校验异常:{},异常类型:{}", t.getMessage(), t.getClass());
        return R.error(BizCodeEnums.UNKNOW_EXCEPTION.getCode(), BizCodeEnums.UNKNOW_EXCEPTION.getMessage());
    }
}
